package com.appspot.codelab.docs.client.content.menus;

import com.appspot.codelab.docs.client.commands.CurrentDocumentCopyCommand;
import com.appspot.codelab.docs.client.commands.CurrentDocumentDeleteCommand;
import com.appspot.codelab.docs.client.commands.CurrentDocumentRenameCommand;
import com.appspot.codelab.docs.client.commands.CurrentDocumentSaveCommand;
import com.appspot.codelab.docs.client.commands.NewDocumentStartCommand;
import com.appspot.codelab.docs.client.commands.SystemShowDialogCommand;
import com.appspot.codelab.docs.client.content.dialogs.DynamicFileListDialog;
import com.appspot.codelab.docs.client.content.dialogs.DynamicUploadDialog;
import com.appspot.codelab.docs.client.content.icons.Icons;
import com.appspot.codelab.docs.client.widgets.DynamicMenuBar;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.RunAsyncCallback;
import com.google.gwt.user.client.rpc.AsyncCallback;

/**
 * Contains a File menu with on-demand loading.
 */
public class DynamicFileMenu extends DynamicMenuBar {

  protected static DynamicFileMenu instance;
	
  /**
   * Retrieves the single instance of this class.
   */
  public static DynamicFileMenu get() {
    if (instance == null) {
      instance = new DynamicFileMenu();
    }
    return instance;
  }
  
  /**
   * Constructs a file menu.
   */
  protected DynamicFileMenu() {
    super(true);
  }

  /**
   * Asynchronously loads the MenuBar's sub items.
   * 
   * @param callback the callback carrying the sub items
   */
  @Override
  protected void getSubMenu(final AsyncCallback<ExtendedMenuItem[]> callback) {
    GWT.runAsync(new RunAsyncCallback() {
		@Override
		public void onFailure(Throwable reason) {
	      callback.onFailure(reason);
		}
		@Override
		public void onSuccess() {
		  callback.onSuccess(new ExtendedMenuItem[] {
			new ExtendedMenuItem(Icons.editorIcons.Blank(), "New", new NewDocumentStartCommand()),
			null,
			new ExtendedMenuItem(Icons.editorIcons.OpenDocument(), "Open", new SystemShowDialogCommand(DynamicFileListDialog.class)),
			new ExtendedMenuItem(Icons.editorIcons.Save(), "Save", new CurrentDocumentSaveCommand(false)),
			new ExtendedMenuItem(Icons.editorIcons.Blank(), "Save as new copy", new CurrentDocumentCopyCommand()),
			new ExtendedMenuItem(Icons.editorIcons.Blank(), "Rename...", new CurrentDocumentRenameCommand()),
			new ExtendedMenuItem(Icons.editorIcons.Blank(), "Delete...", new CurrentDocumentDeleteCommand()),
			null,
			new ExtendedMenuItem(Icons.editorIcons.UploadDocument(), "Upload Files...", new SystemShowDialogCommand(DynamicUploadDialog.class)),
		  });
		}
    });
  }

}
